package techstudy;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.*;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

public class Service {

	private Database database;

	public Service(Database database) {
		this.database = database;
	}

	public boolean query(String query) {
		return database.isAvailable();
	}

	@Override
	public String toString() {
		return "Using database with id: " + String.valueOf(database.getUniqueId());
	}

	@ExtendWith(MockitoExtension.class)
	static public class UnitTest {

		@Mock
		Database databaseMock;

		@Test
		public void testQuery() {
			assertNotNull(databaseMock);
			when(databaseMock.isAvailable()).thenReturn(true);
			Service t = new Service(databaseMock);
			boolean check = t.query("* from t");
			assertTrue(check);
		}
	}

	static public class UnitTest2 {

		Database databaseMock;

		@BeforeEach
		void setUp() throws Exception {
			databaseMock = mock(Database.class);
		}

		@Test
		public void testQuery() {
			assertNotNull(databaseMock);
			System.out.println(databaseMock.isAvailable());
			when(databaseMock.isAvailable()).thenReturn(true);
			System.out.println(databaseMock.isAvailable());
			Service t = new Service(databaseMock);
			boolean check = t.query("* from t");
			assertTrue(check);
		}

		@Test
		public void ensureMockitoReturnsTheConfiguredValue() {

			// define return value for method getUniqueId()
			when(databaseMock.getUniqueId()).thenReturn(80).thenReturn(81);

			Service service = new Service(databaseMock);
			// use mock in test....
			assertEquals(service.toString(), "Using database with id: 80");
			assertEquals(service.toString(), "Using database with id: 81");
		}

	}
}